local proto = require("src.kit.core.proto")
local checker = require("src.kit.core.checker")
--------------------------------------------------
-- @file src/kit/core/timer/timer.lua
-- @desc timer
-- @author doooreyn
-- @date 2020.11.14
-- @more 定时器
--------------------------------------------------
local timer = proto.class("timer")

--
-- @method scheduler
-- @desc 获取cocos调度管理器实例
-- @return cc.Scheduler
--
local function scheduler()
    return cc.Director:getInstance():getScheduler()
end

--
-- @method timer.ctor
-- @desc 定时器构造器
-- @param config table
-- @more config = {
--   on_start(function),
--   on_pause(function),
--   on_stop(function),
--   on_restart(function),
--   on_tick(function),
--   delay(number),
--   tick(number),
--   loops(number/boolean)
-- }
--
function timer:ctor(config)
    -- 设置配置
    self:set_config(config)
    -- 当前已经运行几个tick
    self.ticks = 0
    self.timerid = nil
    self.working = false
end

--
-- @method timer.set_config
-- @desc 配置定时器
-- @param config table
--
function timer:set_config(config)
    checker.expect_type(config, checker.types.table, "timer.set_config")
    checker.expect(self.timerid, nil, "timer.set_config")
    self.config = {
        on_start = config.on_start or function()
            end,
        on_pause = config.on_pause or function()
            end,
        on_stop = config.on_stop or function()
            end,
        on_restart = config.on_restart or function()
            end,
        on_tick = config.on_tick or function()
            end,
        delay = config.delay or 0,
        tick = config.tick or 1,
        loops = config.loops or false
    }
    self:delay(self.config.delay)
end

--
-- @method timer.start
-- @desc 启动定时器
--
function timer:start()
    checker.expect(self.timerid, nil, "timer.start")
    self.timerid = scheduler():schedule()
end

--
-- @method timer.pause
-- @desc 暂停定时器
--
function timer:pause()
    checker.expect_not(self.timerid, nil, "timer.pause")
end

--
-- @method timer.stop
-- @desc 停止定时器
--
function timer:stop()
    checker.expect_not(self.timerid, nil, "timer.stop")
end

--
-- @method timer.restart
-- @desc 重启定时器
--
function timer:restart()
    checker.expect_not(self.timerid, nil, "timer.restart")
end

--
-- @method timer.delay
-- @desc 延时启动定时器
-- @param delay number 延时时间
--
function timer:delay(delay)
    delay = math.max(0, delay or 0)
    self.config.delay = delay
    self:start()
end

return timer
